
package com.cgmnx.admin.web;


import com.cgmnx.admin.common.exception.CgmnxException;
import com.cgmnx.admin.common.util.JacksonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 统一异常处理
 */
@Slf4j
public class GlobalExceptionHandler implements HandlerExceptionResolver, Ordered {

    /**
     * json接口的view
     */
    private static MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
    /**
     * 第三位
     * 不加order会排在最后，DefaultHandlerExceptionResolver会吞掉一些异常（如 参数不正确）返回特定的状态码
     *
     * @see org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser
     */
    private int order = 1;

    /**
     * 处理异常
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception ex) {
        //目前只考虑了json接口
        ModelAndView modelView = new ModelAndView();
        modelView.setView(jsonView);

        // 区分业务异常 和 其他未捕获异常
        if (ex instanceof CgmnxException) {
            CgmnxException exception = (CgmnxException) ex;
            modelView.addObject("ret", Boolean.FALSE);
            modelView.addObject("msg", exception.getMessage());
            // 处理业务异常
            log.error("业务异常:{}", ex.getMessage(), ex);
        } else if (ex instanceof HttpMessageNotReadableException
                || ex instanceof ServletRequestBindingException
                || ex instanceof MissingServletRequestParameterException) {
            modelView.addObject("ret", Boolean.FALSE);
            modelView.addObject("msg", "错误的请求");
        } else {
            modelView.addObject("ret", Boolean.FALSE);
            modelView.addObject("msg", "错误的请求");
            // 处理其他未捕获异常
            log.error("未捕获异常:{}", JacksonMapper.encodeQuietly(request.getParameterMap()), ex);
        }

        return modelView;
    }


    @Override
    public int getOrder() {
        return order;
    }
}